package com.lezijie.seckill.exception;

import com.lezijie.seckill.vo.RespBean;
import com.lezijie.seckill.vo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 自定义异常处理类
 * @author 孙志鹏
 * @createDate 2021/10/24 20:21
 */
@RestControllerAdvice // 处理进入到控制器的异常
public class GlobalExceptionHandler {

    /**
     * 统一处理所有异常
     * @param e 异常类信息
     * @return 响应实体类
     */
    @ExceptionHandler(value = Exception.class)
    public RespBean ExceptionHandler(Exception e) {
        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return RespBean.error(ex.getRespBeanEnum());
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            RespBean respBeanBindError = RespBean.error(RespBeanEnum.BIND_ERROR);
            respBeanBindError.setMessage(bindException.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBeanBindError;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }
}
